/*
 * Login        1.10    2008/02/27
 * 
 * February 27, 2007
 * 
 * Copyright GNU General Public License v3
 */
package StudyBuddy;

import java.util.*;
import java.io.*; 
import javax.swing.*;

/**
 * Login calss, to register and authenticate users.
 * 
 * @version     1.10    27 Feb 2008
 * @author      Rajpreet Bajwa
 */
public class Login {
    
    /** var String to store username to register or authenticate an account */
    String username;
    
    /** var String to store password to register or authenticate an account */
    String password;
   
    /** 
     * Sets the value for username.
     * @param name of type string.
     * void function does not return anything.
     */
    public void getUsername(String name)
    {
        username = name ;
    }   //getUsername
    
    /** 
     * Sets the value for password.
     * @param pass of type string.
     * void function does not return anything.
     */
    public void getPassword(String pass)
    {
        password = pass;
    }   //getPassword
    
    /** 
     * Checks if the username and password entered by the user for registration
     * is the correct length and format. Username must be two characters or 
     * longer and the password must be six characters or longer, both the 
     * username and password must not contain the symbol '&'.  The 
     * checkUsernamePassword calls private functions like checkUsernameLength, 
     * checkPasswordLength, checkSymbol and checkUserexist.  Once all the checks
     * are passed then this functions calls the private function writeInfo to 
     * create the user account.
     */
    public void checkUsernamePassowrd()
    {
        boolean usernameReply = false;
        boolean passwordReply = false;
        boolean checkUserexistReply = true;
        boolean checkSymbolUsernameReply = true;
        boolean checkSymbolPasswordReply = true;
        
        /**
         * calls various functions to check the length and format of the input. 
         */ 
        usernameReply = checkUsernameLength();
        passwordReply = checkPasswordLength();
        checkSymbolUsernameReply = checkSymbol(username);
        checkSymbolPasswordReply = checkSymbol(password);
        
        if ((usernameReply == true) && (passwordReply == true) 
                && (checkSymbolUsernameReply == true) 
                && (checkSymbolPasswordReply == true))
            {
                checkUserexistReply = checkUserexist(username);
                
                if (checkUserexistReply == false)
                {
                    
                    /* if all checks for length and format are passed. */
                    writeInfo();

                    /** 
                     * Display a message box telling the user account 
                     * is created.
                     */
                    JOptionPane.showMessageDialog(null, "Account for " 
                            + username + " createed." );

                }   //if (checkUserexistReply == false)
                else
                {
                    /**
                     * Displaly a message box telling the user that the username 
                     * entred already exists.
                     */
                   JOptionPane.showMessageDialog(null,
                           "Username already in use. " +
                           "Please enter a different Username.");
                }  // else (checkUserexistReply == true)   
             }   //end if ((usernameReply == true) && (passwordReply == true))
        
    }   //checkUsernamePassword
    
    /**
     * Checks the length of the username.
     * @return reply of type boolean.
     */
    private boolean checkUsernameLength()
    {
        int length = 0;             
        boolean reply = false;
          
        length = username.length(); //finds the usernames length
        if (length >= 2)    //checks if the length is greater than or equal to 2
        {
            reply = true;  
        }  
        else
        {   
            JOptionPane.showMessageDialog(null, 
                    "Username must be two charachters or longer.  "
                    + "Username or Password must not contain the symbol '&'. ");
        }   //end else if (length >= 2)
        return reply;   //return the value of reply.  
    }   //checkUsernameLength
    
    /**
     * Checks the length of the password.
     * @return reply of type boolean.
     */
    private boolean checkPasswordLength()
    {
        int length = 0;
        boolean reply = false;
        
        length = password.length(); //finds the password's length
        if (length >= 6)
        {
            reply = true;
        }
        else
        { 
           JOptionPane.showMessageDialog(null,
                   "Password must be six charachters or longer.  " +
                   "Username or Password must not contain the symbol '&'. ");
        }   //end else if (length >= 6)
                
        return reply;   //return the value of reply        
    }   //checkPasswordLength
    
    /**
     * Checks if the input contains the symbol '&'.
     * @param text of type of string
     * @return reply of type boolean
     */
    private boolean checkSymbol(String text)
    {
         boolean checkSymbol = true;    //assuming text does contaion '&'
         boolean reply = false;
         
         checkSymbol = text.contains("&");  //check if input contains '&'
         if (checkSymbol == false)
         {
             reply = true;
         }
         else
         {
             JOptionPane.showMessageDialog(null, 
                     "Username or Password must not contain the symbol '&'. ");
         }  //end else if (checkSymbol == false)
         
         return reply;  //return the value of reply
    }   //checkSymbol
    
    /**
     * Logs in a user with a correct username and password.
     * @return login of type boolean.
     */
    public boolean validateUser()
    {
        String find = username + password;  //username and password to login
        boolean validate = false;
        boolean login = false;
             
        validate = checkUserexist(find);    //check if such a user exists
        if (validate == true)
        {
            JOptionPane.showMessageDialog(null, "Loggin IN");
             
            login = true;   //if login is succesful.
        }
        else
        {
             JOptionPane.showMessageDialog(null, 
                     "Username or Password Incorrect");   
        }   //end else if (validate == true)
        return login;   //return login
    }   //validateUser
    
    /**
     * Checks if a username exists or not.
     * @param name of type string.
     * @return reply of type boolean.
     */
    private boolean checkUserexist(String name)
    {
        String find = name;     //user to find
    	String ans = "0000000"; //ans gets the value of find if user exists
    	String word = null;     //used with the stringTokenizer to store words
        String line = null;     //to store the lines form the file being read
        boolean reply = false;
    	
    	try
    	{
            /** code to read from the text file userAccounts.txt */
            BufferedReader inputStream = new BufferedReader
                    (new FileReader("userAccounts.txt"));

            line = inputStream.readLine();  //reading a line from the file

            while (line != null)    
            { 
                /** 
                 * takes a line and puts it into seperate words when ever the
                 * symbo '&' comes up
                 * Example:
                 * String line = "Mary&had&a&lamb"
                 * System.out.println(line); 
                 * //output is:
                 * "Mary"
                 * "had"
                 * "a"
                 * "lamb"
                 */
                StringTokenizer wordFinder = new StringTokenizer(line,"&");
                while (wordFinder.hasMoreTokens())  //while there are more words
                {
                        word = wordFinder.nextToken(); //get the next word
                        
                        if (word.equals(find))
                        {
                                ans = find;      				
                        }   //end if
                }   //while (wordFinder.hasMoreTokens())
                line = inputStream.readLine();  //get the next line form file
            }
            inputStream.close();    //close the input stream
            if (ans.equals(find))   
            {
                reply = true;
            } //end if
    	}   //end try
        
        /** catch Exceptions */
    	catch(FileNotFoundException e)  
    	{
    		System.out.println("File " + "out.txt" + " not found");	
    	}
    	catch(IOException e) 
    	{
    		System.out.println("Error reading from file out.txt");
    	}   
        return reply;   //return the value in reply
    }   //checkUserexists 

    /**
     * Private funtion that writes the username and password  to the text file
     * userAccounts.txt.  Once the account has been written to this file, the
     * user has completed registering an account.
     */
    private void writeInfo()
    {
        
         FileOutputStream output;   //declare a file output object
                PrintStream print;  //declare a print stream object

                try
                {
                        /** 
                         * Create a new file output stream
                         * connected it to "userAccounts.txt"
                         */
                        output = new FileOutputStream("userAccounts.txt",true);

                        /** Connect print stream to the output stream */
                        print = new PrintStream( output );
                        print.println (username +"&" + username + password);
                            
                         JOptionPane.showMessageDialog(null, 
                                 "Registration complete.");
                }   //end try
                
                /** catch Exception */
                catch (FileNotFoundException e)
                {
                        System.out.println("Error opening the file.  ");
                        System.exit(0);
                }
   }    //writeInfo
}   //Login

